package com.f6.weixin.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.ParserConfigurationException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.f6.utils.HttpClientUtil;
import com.f6.utils.SystemConstans;
import com.f6.weixin.common.vo.KeFu;
import com.f6.weixin.common.vo.SNSUserInfo;
import com.f6.weixin.common.vo.WeixinPayRequestVO;
import com.f6.weixin.common.vo.WeixinUserInfo;

public class WeiXinUtils {
	private static Logger logger = LoggerFactory.getLogger(WeiXinUtils.class);

	private static final String TOKEN = "putongww";

	public static SNSUserInfo getSNSUser(String code, String accessToken, String openId) {
		SNSUserInfo snsuserinfo = WeixinAuthUtil.getSNSUserInfo(accessToken, openId);
		return snsuserinfo;

	}

	public static String createMenu(String accesstoken) {
		String createurl = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + accesstoken;
		// String deleteurl
		// ="https://api.weixin.qq.com/cgi-bin/menu/delete?access_token="+accesstoken;

		JSONObject jsonobj = new JSONObject();
		JSONArray buttons = new JSONArray();
		jsonobj.put("button", buttons);

		JSONObject button1 = new JSONObject();
		// button1.put("type", "click");
		button1.put("type", "view");
		button1.put("name", "点餐");
		// button1.put("key", "尚未开通，敬请谅解");
		button1.put("url", createOAuthURI(SystemConstans.WEXIN_DOMAIN + SystemConstans.QT + "/prodlist.do"));

		// ------------------
		JSONObject button2 = new JSONObject();
		button2.put("name", "我的");

		JSONArray subbuttons21 = new JSONArray();
		button2.put("sub_button", subbuttons21);

		JSONObject button21 = new JSONObject();
		button21.put("type", "view");
		button21.put("name", "我的二维码");
		button21.put("url", createOAuthURI(SystemConstans.WEIXIN_AUTH_REIDRECT_URL_QRCODE));
		subbuttons21.add(button21);

		JSONObject button22 = new JSONObject();
		button22.put("type", "view");
		button22.put("name", "我的信息");
		button22.put("url", createOAuthURI(SystemConstans.WEIXIN_AUTH_REIDRECT_URL_USER_DETAIL));
		subbuttons21.add(button22);

		// ------------------
		JSONObject button3 = new JSONObject();
		button3.put("name", "关于我们");
		JSONArray subbuttons31 = new JSONArray();
		button3.put("sub_button", subbuttons31);

		JSONObject button31 = new JSONObject();
		button31.put("type", "view");
		button31.put("name", "关于我们");
		button31.put("url", "http://www.putong365.com/");
		subbuttons31.add(button31);

		JSONObject button32 = new JSONObject();
		button32.put("type", "view");
		button32.put("name", "官网");
		button32.put("url", "http://www.putong365.com/");
		subbuttons31.add(button32);

		JSONObject button33 = new JSONObject();
		button33.put("type", "view");
		button33.put("name", "标准化中央厨房");
		button33.put("url", "http://www.putong365.com/");
		subbuttons31.add(button33);

		buttons.add(button1);
		buttons.add(button2);
		buttons.add(button3);

		String resultjson = jsonobj.toJSONString();
		logger.info("------------------------------");
		logger.info(resultjson);
		String result = HttpClientUtil.httpPostRequest(createurl, resultjson);
		logger.info(result);
		return resultjson;
		// JSONObject jsonobj = JSONObject.parseObject(result);

	}

	public static void getUserList(String accesstoken) {
		String url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + accesstoken + "&next_openid=";
		String result = HttpClientUtil.httpGetRequest(url);
		JSONObject jsonobj = JSONObject.parseObject(result);
		String numberOfUser = String.valueOf(jsonobj.get("total"));
		String countUser = String.valueOf(jsonobj.get("count"));

		JSONObject data = (JSONObject) jsonobj.get("data");
		JSONArray arry = data.getJSONArray("openid");
		Iterator it = arry.iterator();

		for (; it.hasNext();) {
			String openid = (String) it.next();
			logger.info(openid);
		}

		// System.out.println(result);
	}

	public static String createOAuthURI(String redirecturl) {
		String scope = "snsapi_base";
		// String scope="snsapi_userinfo";
		String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + SystemConstans.APPID + "&redirect_uri="
				+ urlEncodeUTF8(redirecturl) + "&code=CODE&response_type=code&scope=" + scope + "&statue=1#wechat_redirect";
		return url;
	}

	public static String urlEncodeUTF8(String source) {
		String result = source;
		try {
			result = java.net.URLEncoder.encode(source, "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	public static WeixinUserInfo getUserDetail(String accesstoken, String openid) {
		String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + accesstoken + "&openid=" + openid;
		String result = HttpClientUtil.httpGetRequest(url);

		JSONObject jsonobj = JSONObject.parseObject(result);
		// Set keyset = jsonobj.keySet();
		// Iterator it = keyset.iterator();
		WeixinUserInfo user = new WeixinUserInfo();
		try {

			user.setOpenId(jsonobj.getString("openid"));
			user.setSubscribe(jsonobj.getIntValue("subscribe"));
			user.setSubscribeTime(jsonobj.getString("subscribe_time"));
			user.setNickname(jsonobj.getString("nickname"));
			user.setSex(jsonobj.getIntValue("sex"));
			user.setCity(jsonobj.getString("city"));
			user.setProvince(jsonobj.getString("province"));
			user.setLanguage(jsonobj.getString("language"));
			user.setHeadImgUrl(jsonobj.getString("headimageurl"));
		} catch (Exception e) {
			if (0 == user.getSubscribe()) {
				logger.info("用户{}已经取消关注", user.getOpenId());
			} else {
				int errorCode = jsonobj.getIntValue("errcode");
				String errorMsg = jsonobj.getString("errmsg");
				logger.error("获取用户信息失败 errcode:{}  errmsg:{}", errorCode, errorMsg);
			}
		}
		// for (; it.hasNext();) {
		// String key = String.valueOf(it.next());
		// logger.info(key + "---" + String.valueOf(jsonobj.get(key)));
		// }

		// System.out.println(result);
		return user;
	}

	public static String getTempQRCode(String accesstoken, String parameter) {
		String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + accesstoken;

		JSONObject jsonParam = new JSONObject();
		// {"expire_seconds": 604800, "action_name": "QR_SCENE", "action_info":
		// {"scene": {"scene_id": 123}}}

		jsonParam.put("expire_seconds", 1800);
		jsonParam.put("action_name", "QR_SCENE");

		JSONObject actioninfojsonParam = new JSONObject();
		JSONObject scenejson = new JSONObject();
		scenejson.put("scene_id", parameter);

		actioninfojsonParam.put("scene", scenejson);

		jsonParam.put("action_info", actioninfojsonParam);
		System.out.println("==>" + jsonParam.toJSONString());
		String result = HttpClientUtil.httpPostRequest(url, jsonParam.toJSONString());
		JSONObject jsonobj = JSONObject.parseObject(result);
		String ticket = (String) jsonobj.get("ticket");

		String expireSeconds = String.valueOf(jsonobj.get("expire_seconds"));
		String imageurl = (String) jsonobj.get("url");

		String requestimage = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + ticket;

		return requestimage;

	}

	public static String getPermQRCode(String accesstoken, String parameter) {
		String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + accesstoken;
		JSONObject jsonParam = new JSONObject();
		jsonParam.put("action_name", "QR_LIMIT_SCENE");

		JSONObject actioninfojsonParam = new JSONObject();
		JSONObject scenejson = new JSONObject();
		scenejson.put("scene_str", parameter);

		actioninfojsonParam.put("scene", scenejson);

		jsonParam.put("action_info", actioninfojsonParam);
		System.out.println("==>" + jsonParam.toJSONString());
		String result = HttpClientUtil.httpPostRequest(url, jsonParam.toJSONString());
		JSONObject jsonobj = JSONObject.parseObject(result);
		String ticket = (String) jsonobj.get("ticket");

		String expireSeconds = String.valueOf(jsonobj.get("expire_seconds"));
		String imageurl = (String) jsonobj.get("url");

		String requestimage = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + ticket;

		return requestimage;

	}

	public static String refreshAccessToken(HttpServletRequest request, String appid, String appsecret) {
		String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + appsecret;
		String result = HttpClientUtil.httpGetRequest(url);
		JSONObject jsonobj = JSONObject.parseObject(result);
		String accessToken = (String) jsonobj.get("access_token");
		request.getSession().setAttribute(SystemConstans.WEIXIN_ACCESS_TOKEN, accessToken);
		return accessToken;
	}

	public static String getAccessToken(String appid, String appsecret) {
		String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + appsecret;
		String result = HttpClientUtil.httpGetRequest(url);
		JSONObject jsonobj = JSONObject.parseObject(result);
		String accessToken = (String) jsonobj.get("access_token");
		return accessToken;
	}

	public static boolean checkSignature(String signature, String timestamp, String nonce) {
		String token = TOKEN;
		String[] paramArr = new String[] { token, timestamp, nonce };
		Arrays.sort(paramArr);
		String content = paramArr[0].concat(paramArr[1]).concat(paramArr[2]);
		MessageDigest md;
		String ciphertext = null;
		try {
			md = MessageDigest.getInstance("SHA-1");
			byte[] digest = md.digest(content.getBytes());
			ciphertext = byteToStr(digest);
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return ciphertext != null ? ciphertext.equals(signature.toUpperCase()) : false;
	}

	private static String byteToStr(byte[] str) {
		StringBuilder strdigest = new StringBuilder();
		int length = str.length;
		for (int i = 0; i < length; i++) {
			strdigest.append(byteToHexStr(str[i]));
		}
		return strdigest.toString();
	}

	private static String byteToHexStr(byte b) {
		// TODO Auto-generated method stub
		char[] digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
		char[] ob = new char[2];
		ob[0] = digit[(b >>> 4) & 0X0F];
		ob[1] = digit[b & 0X0F];
		String s = new String(ob);
		return s;
	}

	public static String utf8str(String str) {
		String result = null;
		try {
			result = new String(str.toString().getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

	public static List<KeFu> getKeFuList(String accesstoken) {
		String url = "https://api.weixin.qq.com/cgi-bin/customservice/getkflist?access_token=" + accesstoken;
		String result = HttpClientUtil.httpGetRequest(url);
		JSONArray kefus = JSONObject.parseArray(result);

		Iterator it = kefus.iterator();
		List<KeFu> kefulist = new ArrayList<KeFu>();
		for (; it.hasNext();) {
			JSONObject obj = (JSONObject) it.next();
			KeFu kefu = new KeFu();
			kefu.setKf_account(obj.getString("kf_account"));
			kefu.setKf_headimgurl(obj.getString("kf_headimgurl"));
			kefu.setKf_id(obj.getString("kf_id"));
			kefu.setKf_nick(obj.getString("kf_nick"));
			kefulist.add(kefu);
		}
		return kefulist;
	}

	public static String addKeFu(String accesstoken, KeFu kefu) {
		String url = "https://api.weixin.qq.com/customservice/kfaccount/add?access_token=" + accesstoken;
		JSONObject obj = new JSONObject();
		obj.put("kf_account", kefu.getKf_account());
		obj.put("kf_nick", kefu.getKf_nick());
		obj.put("password", kefu.getPassword());
		return HttpClientUtil.httpPostRequest(url, obj.toJSONString());
	}

	public static String removeKeFu(String accesstoken, String accountid) {
		String url = "https://api.weixin.qq.com/customservice/kfaccount/del?access_token=" + accesstoken + "&kf_account=" + accountid;
		return HttpClientUtil.httpGetRequest(url);
	}

	public static String zhifuTicket(String accesstoken) {
		String ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";
		String requestUrl = ticket_url.replace("ACCESS_TOKEN", accesstoken);
		// 发起GET请求获取凭证
		String response = HttpClientUtil.httpGetRequest(requestUrl);
		JSONObject jsonObject = JSONObject.parseObject(response);

		return "";
	}

	public static String zhifuSignature() {
		return "";
	}

	public static void main(String[] args) {
		String accessToken = "mFUkYfxrrvyczzoPJbK6lp6kE2XFB3iFwQ8Tpq6ljO2vJfDMw0racsTvXXNn8NS4HWBGMBEv0HVWOrJVAtkIVn35EEYHFMZSeeCienXGF1uQUYilNEnWHoFHubWr8gWFGYGeABACUC";
		String tt = "1";
		if ("1".equals(tt)) {
			accessToken = getAccessToken(SystemConstans.APPID, SystemConstans.APPSECRET);
			System.out.println("accesstoken==========:" + accessToken);
		}
		// getUserDetail(accessToken, "o5YTowhqsjHHD101h9CBYJFxSEHc");
		createMenu(accessToken);

		String result = getTempQRCode(accessToken, "12345");
		System.out.println(result);
		// paytest();
	}

	private static void paytest() {
		try {
			// TODO Auto-generated method stub
			WeixinPayRequestVO reqData = new WeixinPayRequestDataBuilder("appid", "mch_id", "body", "out_trade_no", 1, "spbill_create_ip",
					"notify_url", "JSAPI").setOpenid("openid").build();
			String res = WexinPayHttpService.doPost(WeixinConfigure.UNIFIED_ORDER_API, reqData);

			Map<String, Object> resultmap = WeixinXMLParser.getMapFromXML(res);
			Iterator it = resultmap.keySet().iterator();
			for (; it.hasNext();) {
				String key = (String) it.next();
				Object value = resultmap.get(key);
				System.out.println("key:" + key + "--value:" + value);
			}
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public String getQRCode() {
		String accesstoken = getAccessToken(SystemConstans.APPID, SystemConstans.APPSECRET);
		String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + accesstoken;
		String json = "{\"action_name\":\"QR_LIMIT_SCENE\", \"action_info\": {\"scene\": {\"scene_id\": 123}}}";
		String result = HttpClientUtil.httpPostRequest(url, json);
		return result;

	}

	 
	
}
